package com.shirospringboot.controller;

import com.shirospringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author fzp
 */
@Controller
public class MyController {
    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String userAdd(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String userUpdate(){
        return "user/update";
    }

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("/unth")
    public String unth(){
        return "unth";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password );
        try {
            subject.login(usernamePasswordToken);
            model.addAttribute("msg","登录成功");
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(Model model){
        Subject subject=SecurityUtils.getSubject();
        HttpSession session= (HttpSession) subject.getSession();
        session.invalidate();
        model.addAttribute("msg","注销成功");
        return "index";
    }
}
